package icu.wangrui.bookstore.service.impl;

import icu.wangrui.bookstore.mapper.UserMapper;
import icu.wangrui.bookstore.pojo.User;
import icu.wangrui.bookstore.service.IUserService;
import icu.wangrui.bookstore.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MD5Util md5Util;

    @Override
    public User queryUserByName(String uname, String upwd) {

        if (uname != null && upwd != null) {
            User user = userMapper.checkUserByName(uname);
            // 执行密码加密，得到加密后的密码
            String md5Password = md5Util.getMd5Password(upwd, user.getSalt());
            return userMapper.queryUserByName(uname,md5Password);
        }
        return null;
    }

    @Override
    public boolean userRegister(User user) {
        // 生成随机盐
        String salt = UUID.randomUUID().toString().toUpperCase();
        // 执行密码加密，得到加密后的密码

        String md5Password = md5Util.getMd5Password(user.getUpwd(), salt);
        // 将盐和加密后的密码封装到user中
        user.setUpwd(md5Password);
        user.setSalt(salt);
        return userMapper.userRegister(user);
    }

    @Override
    public Boolean checkUserByName(String uname) {
        User user = userMapper.checkUserByName(uname);
        if (user == null) {
            return false;
        }
        return true;
    }

    @Override
    public Boolean checkUserByPhone(String phone) {
        User user = userMapper.checkUserByPhone(phone);
        if (user == null) {
            return false;
        }
        return true;
    }

    @Override
    public User checkUserByEmail(String email) {
        User user = userMapper.checkUserByEmail(email);
        return user;
    }

    @Override
    public Boolean updateUserPasswordbyPhone(String phone, String cpwd) {
        // 生成随机盐
        String salt = UUID.randomUUID().toString().toUpperCase();
        // 执行密码加密，得到加密后的密码
        String md5Password = md5Util.getMd5Password(cpwd, salt);
        // 将盐和加密后的密码封装到user中
        User user = new User();
        user.setSalt(salt);
        user.setPhone(phone);
        user.setUpwd(md5Password);
        return userMapper.updateUserPasswordbyPhone(user);
    }
}
